import collections


class Solution(object):
    def findBlackPixel(self, picture, target):
        """
        :type picture: List[List[str]]
        :type target: int
        :rtype: int
        """
        m = len(picture)
        n = len(picture[0])
        x_count = [picture[i].count('B') for i in range(m)]
        y_count = [[picture[i][j] for i in range(m)].count('B') for j in range(n)]
        d = collections.defaultdict(set)
        for i in range(m):
            d[tuple(picture[i])].add(i)
        cell = {}
        index = 1
        for key in d:
            for item in d[key]:
                cell[item] = index
            index += 1
        total = 0
        for j in range(n):
            if y_count[j] == target:
                now_set = set()
                now_index = 0
                for i in range(m):
                    if picture[i][j] == 'B':
                        if x_count[i] != target:
                            break
                        if not now_index:
                            now_index = cell[i]
                            now_set.add(i)
                        else:
                            if now_index != cell[i]:
                                break
                            else:
                                now_set.add(i)
                if len(now_set) == target:
                    total += target
        return total


data = Solution()
picture = [["W", "B", "W", "B", "B", "W"], ["W", "B", "W", "B", "B", "W"], ["W", "B", "W", "B", "B", "W"],
           ["W", "W", "B", "W", "B", "W"]]
target = 3
print(data.findBlackPixel(picture, target))
picture = [["W", "W", "B"], ["W", "W", "B"], ["W", "W", "B"]]
target = 1
print(data.findBlackPixel(picture, target))
picture = [["W", "B", "W", "B", "B", "W"], ["W", "B", "W", "B", "B", "W"], ["W", "B", "W", "B", "B", "W"],
           ["W", "W", "B", "B", "B", "W"]]
target = 3
print(data.findBlackPixel(picture, target))
picture = [["W", "B", "W", "B", "B", "W"], ["W", "B", "W", "B", "B", "W"], ["W", "B", "W", "B", "W", "W"],
           ["W", "W", "B", "W", "B", "W"]]
target = 3
print(data.findBlackPixel(picture, target))
picture = [["W", "B", "W", "B", "B", "W"], ["W", "B", "W", "B", "B", "W"], ["W", "B", "W", "B", "W", "W"],
           ["W", "W", "B", "W", "B", "W"]]
target = 1
print(data.findBlackPixel(picture, target))